import 'dart:convert';
import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:wallpaper/api/mobile.dart';
import 'package:wallpaper/components/video/video_list.dart';
import 'package:wallpaper/model/random_video_base.dart';

class RandomVideoList extends StatefulWidget {
  final int format;
  const RandomVideoList({super.key, required this.format});

  @override
  State<RandomVideoList> createState() => _RandomVideoListState();
}

class _RandomVideoListState extends State<RandomVideoList> {
  final List<VideoBaseInfo> videos = [];
  bool isLoading = false;
  int page = 1;
  int limit = 20;

  Future<void> getData() async {
    if (!mounted) return;
    setState(() {
      isLoading = true;
    });
    try {
      Response res = await mobileRandom(
          page: page, limit: limit, format: widget.format, screen: 2);
      // 非标准json格式，手动解析
      Map<String, dynamic> data = json.decode(res.data);
      if (data['code'] == 1) {
        for (var i = 0; i < data['data'].length; i++) {
          VideoBaseInfo video = VideoBaseInfo(
            width: data['data'][i]['width'],
            height: data['data'][i]['height'],
            cover: data['data'][i]['cover'],
            url: data['data'][i]['url'],
            tag:
                data['data'][i]['tag'].replaceAll('#', '').replaceAll('默认', ''),
          );
          setState(() {
            videos.add(video);
          });
        }
      }
    } catch (e) {
      print(e);
    } finally {
      setState(() {
        isLoading = false;
      });
    }
  }

  @override
  void initState() {
    super.initState();
    getData();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return VideoList(
        videoList: videos,
        isLoading: isLoading,
        onImageBottomLoading: () {
          if (isLoading) return;
          page++;
          getData();
        },
        onImageListRefresh: () {
          setState(() {
            page = 1;
            videos.clear();
          });
          getData();
        });
  }
}
